// pages/getShareImg/getShareImg.js
var app = getApp();
const getShareImgUrl = '/Activity/getQrCode';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: 1, //是否显示加载中图标
    isUseHttp: 0,
    QRCodeImg: '',
    QRCodeImgHttp: ''
  },
  //获取分享图
  getShareImg: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type
    }
    app.post(getShareImgUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          isLoading: 0,
          QRCodeImg: res.data.image_https,
          QRCodeImgHttp: res.data.image_http
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  // 保存图片
  saveImg: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.downloadFile({
      url: _this.data.QRCodeImg,
      success: function(res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            console.log(res)
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            console.log(res)
            console.log('fail')
          }
        })
      },
      fail: function() {
        console.log('fail')
      }
    })
  },
  // 预览图片
  previewImg: function() {
    var _this = this;
    var urls;
    if (_this.data.isUseHttp == 1) {
      urls = [_this.data.QRCodeImgHttp]
    } else {
      urls = [_this.data.QRCodeImg]
    }
    wx.previewImage({
      current: _this.data.QRCodeImg, // 当前显示图片的http链接
      urls: urls
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    _this.setData({
      activity_time_title: options.activity_time_title,
      activity_title: options.activity_title,
      activity_award_money: options.activity_award_money,
      activity_award_unit: options.activity_award_unit
    })
    wx.getSystemInfo({
      success: function(res) {
        if (res.system.search('iOS') == -1) {
          _this.setData({
            isUseHttp: 1
          })
        } else {
          _this.setData({
            isUseHttp: 0
          })
        }
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        })
      }
    });
    _this.loop();
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getShareImg();
    }
  }
})